/**
 * 语音识别系统 - 工具函数库
 */

// 音效系统
const SoundEffects = {
    // 内置音效生成器
    generateClick: function() {
        try {
            const context = new (window.AudioContext || window.webkitAudioContext)();
            const oscillator = context.createOscillator();
            const gain = context.createGain();
            
            oscillator.connect(gain);
            gain.connect(context.destination);
            
            oscillator.type = 'sine';
            oscillator.frequency.value = 800;
            gain.gain.value = 0.1;
            
            oscillator.start(0);
            
            gain.gain.exponentialRampToValueAtTime(0.001, context.currentTime + 0.1);
            oscillator.stop(context.currentTime + 0.1);
        } catch(e) {
            console.log('音效播放失败', e);
        }
    },
    
    generateBeep: function(frequency = 500, duration = 200, volume = 0.1, type = 'sine') {
        try {
            const context = new (window.AudioContext || window.webkitAudioContext)();
            const oscillator = context.createOscillator();
            const gain = context.createGain();
            
            oscillator.connect(gain);
            gain.connect(context.destination);
            
            oscillator.type = type;
            oscillator.frequency.value = frequency;
            gain.gain.value = volume;
            
            oscillator.start(0);
            
            setTimeout(() => {
                gain.gain.exponentialRampToValueAtTime(0.001, context.currentTime + 0.1);
                setTimeout(() => {
                    oscillator.stop();
                }, 100);
            }, duration);
        } catch(e) {
            console.log('音效播放失败', e);
        }
    },
    
    // 预定义音效
    buttonClick: function() {
        this.generateClick();
    },
    
    success: function() {
        this.generateBeep(800, 100, 0.1, 'sine');
        setTimeout(() => {
            this.generateBeep(1200, 100, 0.1, 'sine');
        }, 100);
    },
    
    error: function() {
        this.generateBeep(300, 200, 0.1, 'sawtooth');
    },
    
    notification: function() {
        this.generateBeep(600, 80, 0.1, 'sine');
        setTimeout(() => {
            this.generateBeep(800, 80, 0.1, 'sine');
        }, 100);
    }
};

// 通知系统
const Notifications = {
    show: function(message, type = 'info', duration = 3000) {
        // 创建通知元素
        const notification = document.createElement('div');
        notification.className = `notification notification-${type}`;
        notification.textContent = message;
        
        // 添加到DOM
        const container = document.querySelector('.notification-container') || 
                          (() => {
                              const cont = document.createElement('div');
                              cont.className = 'notification-container';
                              cont.style.position = 'fixed';
                              cont.style.top = '20px';
                              cont.style.right = '20px';
                              cont.style.zIndex = '9999';
                              document.body.appendChild(cont);
                              return cont;
                          })();
        
        container.appendChild(notification);
        
        // 显示动画
        setTimeout(() => {
            notification.style.opacity = '1';
            notification.style.transform = 'translateX(0)';
        }, 10);
        
        // 自动消失
        setTimeout(() => {
            notification.style.opacity = '0';
            notification.style.transform = 'translateX(100%)';
            
            // 从DOM中移除
            setTimeout(() => {
                container.removeChild(notification);
                // 如果容器为空，也移除容器
                if (container.children.length === 0) {
                    document.body.removeChild(container);
                }
            }, 300);
        }, duration);
        
        // 根据类型播放适当音效
        switch(type) {
            case 'success':
                SoundEffects.success();
                break;
            case 'error':
                SoundEffects.error();
                break;
            default:
                SoundEffects.notification();
        }
        
        return notification;
    },
    
    success: function(message, duration) {
        return this.show(message, 'success', duration);
    },
    
    error: function(message, duration) {
        return this.show(message, 'error', duration);
    },
    
    info: function(message, duration) {
        return this.show(message, 'info', duration);
    },
    
    warning: function(message, duration) {
        return this.show(message, 'warning', duration);
    }
};

// 检测浏览器支持
function checkBrowserSupport() {
    if (!('WebSocket' in window)) {
        Notifications.error('您的浏览器不支持WebSocket，请更换浏览器');
        return false;
    }
    return true;
}

// 添加音效到按钮
function addSoundToButtons() {
    const buttons = document.querySelectorAll('button');
    buttons.forEach(button => {
        button.addEventListener('click', () => {
            SoundEffects.buttonClick();
        });
    });
}

// 检测移动设备
function isMobileDevice() {
    return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
}

// 格式化日期时间
function formatDateTime(date = new Date()) {
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
    });
}

// 导出文本为文件
function exportToFile(text, filename) {
    const blob = new Blob([text], { type: 'text/plain;charset=utf-8' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.style.display = 'none';
    a.href = url;
    a.download = filename;
    document.body.appendChild(a);
    a.click();
    setTimeout(() => {
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
    }, 100);
}

// 初始化页面
document.addEventListener('DOMContentLoaded', () => {
    // 检查浏览器支持
    checkBrowserSupport();
    
    // 添加按钮音效
    addSoundToButtons();
    
    // 根据设备类型调整UI
    if (isMobileDevice()) {
        document.body.classList.add('mobile-device');
    }
}); 